"""
@file: RoleService.py
@author: lingdubing
@desc: 角色设施文件
@character: utf-8
"""

from ..models.models import Role
from .BaseService import BaseService
from typing import Optional, Tuple, List
from sqlmodel import select, func

class RoleService(BaseService[Role]):
    def __init__(self):
        super().__init__(Role, id_field="role_id")


    def get_role_by_role_id(self, role_id: int) -> Optional[Role]:
        """根据角色role_id获取角色，由于role_id字段不再是primary_key，所以需要重新写此方法，不要用父类的get_by_id方法"""
        with self.get_session() as session:
            statement = select(Role).where(Role.role_id == role_id)
            return session.exec(statement).first()


    def get_role_list(self, page: int, page_size: int, role_id: Optional[str] = None,
                      role_name: Optional[str] = None) -> Tuple[List[Role], int]:
        """获取角色列表（分页）"""
        if page <= 1:
            page = 1

        offset = (page - 1) * page_size
        with self.get_session() as session:
            # 查询分页数据
            total_statement = select(self.model)

            if role_id is not None:
                total_statement = total_statement.where(Role.role_id == role_id)
            if role_name is not None:
                total_statement = total_statement.where(Role.role_name == role_name)

            statement = total_statement.offset(offset).limit(page_size)

            items = session.exec(statement).all()


            # 查询所有数据总数
            total_statement = select(func.count()).select_from(total_statement)
            total = session.exec(total_statement).one()

            return items, total
